package com.aps.server.service;

import cn.hutool.core.lang.copier.Copier;
import com.aps.common.boot.CoreApplicationContext;
import com.aps.common.service.TestGenericService;
import com.aps.server.entity.BasicProduct;
import com.aps.server.mapper.BasicProductMapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 产品信息服务类
 * 提供产品信息相关的业务逻辑处理
 */
@Slf4j
@Service
public class BasicProductService extends TestGenericService {
    @Resource
    BasicProductMapper basicProductMapper;


    /**
     * 创建产品信息
     *
     * @param basicProduct 产品信息
     * @return 是否创建成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean createProduct(BasicProduct basicProduct) {
        // 自动设置租户ID
        if (basicProduct.getTenantId() == null || basicProduct.getTenantId().trim().isEmpty()) {
            basicProduct.setTenantId(getCurrentTenantId());
        }
        basicProduct.setCreateTime(LocalDateTime.now());
        basicProduct.setUpdateTime(LocalDateTime.now());
        if(StringUtils.isBlank(basicProduct.getProductCode())) {
            //编码未填写
            return false;
        }
        List<BasicProduct> basicProducts = queryBasicProductByProductCode(Collections.singletonList(basicProduct.getProductCode()));
        if(CollectionUtils.isEmpty(basicProducts)) {
            //do insert
            int result = basicProductMapper.insert(basicProduct);
            log.info("创建产品信息结果: {}, 产品ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", basicProduct.getId(), basicProduct.getTenantId());
            return result > 0;
        }
        log.info("创建产品信息结果: {}, 存在相同的产品code: {}, 租户ID: {}", "失败", basicProduct.getProductCode(), basicProduct.getTenantId());
        return false;
    }

    //新增、编辑 校验编号是否存在，存在则返回对应 存在的数据
    public List<BasicProduct> queryBasicProductByProductCode(List<String> productCodes) {
        if(CollectionUtils.isEmpty(productCodes)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<BasicProduct> productLambdaQueryWrapper = new LambdaQueryWrapper<BasicProduct>()
                .eq(BasicProduct::getTenantId, getCurrentTenantId())
                .in(BasicProduct::getProductCode, productCodes);
        return basicProductMapper.selectList(productLambdaQueryWrapper);
    }

    /**
     * 更新产品信息
     *
     * @param basicProduct 产品信息
     * @return 是否更新成功
     */
    public boolean updateProduct(BasicProduct basicProduct) {
        basicProduct.setUpdateTime(LocalDateTime.now());

        QueryWrapper<BasicProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", basicProduct.getId()).eq("tenant_id", basicProduct.getTenantId());

        //查询原数据
        List<BasicProduct> basicProductss = basicProductMapper.selectList(Wrappers.lambdaQuery(BasicProduct.class).eq(BasicProduct::getId, basicProduct.getId()).eq(BasicProduct::getTenantId, basicProduct.getTenantId()));
        BasicProduct original = basicProductss.get(0);
        //编码没变过，直接修改
        if(StringUtils.equals(original.getProductCode(), basicProduct.getProductCode())) {
            int result = basicProductMapper.update(basicProduct, queryWrapper);
            log.info("更新产品信息结果: {}, 产品ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", basicProduct.getId(), basicProduct.getTenantId());
            return result > 0;
        }
        //变过编码，需要校验一下编码
        List<BasicProduct> basicProducts = queryBasicProductByProductCode(Collections.singletonList(basicProduct.getProductCode()));
        if(CollectionUtils.isEmpty(basicProducts)) {
            //do insert
            int result = basicProductMapper.update(basicProduct, queryWrapper);
            log.info("更新产品信息结果: {}, 产品ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", basicProduct.getId(), basicProduct.getTenantId());
            return result > 0;
        }
        log.info("更新产品信息结果: {}, 存在相同的产品code: {}, 租户ID: {}", "失败", basicProduct.getProductCode(), basicProduct.getTenantId());
        return false;
    }

    /**
     * 删除产品信息
     *
     * @param id 产品ID
     * @return 是否删除成功
     */
    public boolean deleteProduct(String id) {
        String tenantId = getCurrentTenantId();
        return deleteProduct(id, tenantId);
    }

    /**
     * 根据ID和租户ID删除产品信息
     *
     * @param id 产品ID
     * @param tenantId 租户ID
     * @return 是否删除成功
     */
    public boolean deleteProduct(String id, String tenantId) {
        QueryWrapper<BasicProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("tenant_id", tenantId);

        int result = basicProductMapper.delete(queryWrapper);
        log.info("删除产品信息结果: {}, 产品ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", id, tenantId);
        return result > 0;
    }

    /**
     * 查询当前租户的产品列表
     *
     * @return 产品列表
     */
    public List<BasicProduct> getProductsByTenantId(String productName,String productCode , String productType) {
        String tenantId = getCurrentTenantId();
        return getProductsByTenantId(tenantId,productCode,productName ,productType);
    }

    /**
     * 根据租户ID查询产品列表
     *
     * @param tenantId 租户ID
     * @return 产品列表
     */
    private List<BasicProduct> getProductsByTenantId(String tenantId , String productCode ,String productName , String productType) {
        LambdaQueryWrapper<BasicProduct> wrapper = Wrappers.lambdaQuery(BasicProduct.class).eq(BasicProduct::getTenantId, tenantId);
        if(StringUtils.isNotBlank(productCode)) {
            wrapper.like(BasicProduct::getProductCode, productCode);
        }
        if(StringUtils.isNotBlank(productName)) {
            wrapper.like(BasicProduct::getProductName, productName);
        }
        if(StringUtils.isNotBlank(productType)) {
            wrapper.like(BasicProduct::getProductType, productType);
        }
        List<BasicProduct> basicProducts = basicProductMapper.selectList(wrapper);
        log.info("根据租户ID查询产品列表, 租户ID: {}, 数量: {}", tenantId, basicProducts.size());
        return basicProducts;
    }


    /**
     * 根据租户ID分页查询产品列表
     *
     * @param current 当前页
     * @param size 每页大小
     * @param productCode 产品编号
     * @param productName 产品名称
     * @return 分页产品列表
     */
    public IPage<BasicProduct> getProductsByTenantIdPage(int current, int size, String productName, String productCode) {
        Page<BasicProduct> page = new Page<>(current, size);
        String tenantId = getCurrentTenantId();
        LambdaQueryWrapper<BasicProduct> wrapper = Wrappers.lambdaQuery(BasicProduct.class)
                .eq(BasicProduct::getTenantId, tenantId)
                .like(BasicProduct::getProductCode, productCode)
                .or()
                .like(BasicProduct::getProductName, productName);
        IPage<BasicProduct> basicProductPage = basicProductMapper.selectPage(page, wrapper);
        log.info("分页查询产品列表, 租户ID: {}, 当前页: {}, 每页大小: {}, 总数: {}", tenantId, current, size, basicProductPage.getTotal());
        return basicProductPage;
    }


    /**
     * 根据产品类型查询产品列表
     *
     * @param productType 产品类型
     * @param tenantId 租户ID
     * @return 产品列表
     */
    public List<BasicProduct> getProductsByProductType(String productType, String tenantId) {
        List<BasicProduct> products = basicProductMapper.selectByProductType(productType, tenantId);
        log.info("根据产品类型查询产品列表, 产品类型: {}, 租户ID: {}, 数量: {}", productType, tenantId, products.size());
        return products;
    }

    /**
     * 统计租户下的产品数量
     *
     * @param tenantId 租户ID
     * @return 产品数量
     */
    public Long countProductsByTenantId(String tenantId) {
        Long count = basicProductMapper.countByTenantId(tenantId);
        log.info("统计租户产品数量, 租户ID: {}, 数量: {}", tenantId, count);
        return count;
    }

    /**
     * 批量创建产品信息
     *
     * @param products 产品信息列表
     * @return 成功创建的数量
     */
    public int batchCreateProducts(List<BasicProduct> products) {
        if (products == null || products.isEmpty()) {
            return 0;
        }

        String tenantId = getCurrentTenantId();
        LocalDateTime now = LocalDateTime.now();

        int successCount = 0;
        for (BasicProduct product : products) {
            try {
                if (product.getTenantId() == null || product.getTenantId().trim().isEmpty()) {
                    product.setTenantId(tenantId);
                }
                product.setCreateTime(now);
                product.setUpdateTime(now);

                int result = basicProductMapper.insert(product);
                if (result > 0) {
                    successCount++;
                }
            } catch (Exception e) {
                log.error("批量创建产品信息失败, 产品名称: {}", product.getProductName(), e);
            }
        }

        log.info("批量创建产品信息完成, 总数: {}, 成功: {}", products.size(), successCount);
        return successCount;
    }
}
